package com.uyaer.magic.res
{
	import com.uyaer.magic.utils.HashMap;
	import com.uyaer.magic.utils.Utils;
	
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	import starling.textures.Texture;
	import starling.textures.TextureAtlas;
	
	public class LoadManager
	{
		private static var myinstance:LoadManager = new LoadManager();
		private var urlLoader:URLLoader;
		private var loader:Loader;
		private var resReceiverList:Vector.<Receiver> = new Vector.<Receiver>();
		private var currReceiver:Receiver;
		
		private var isLoading:Boolean = false; //是否在进行加载
		private var loadedResMap:HashMap = new HashMap();
		
		private var loadingURI:String = "";
		private var isLoader:Boolean = true;
		public function LoadManager()
		{
			urlLoader = new URLLoader();
			urlLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR,onError);
			urlLoader.addEventListener(IOErrorEvent.IO_ERROR,onError);
			urlLoader.addEventListener(ProgressEvent.PROGRESS,onProgress);
			urlLoader.addEventListener(Event.COMPLETE,onLoadOver);
			loader = new Loader();
			loader.contentLoaderInfo.addEventListener(SecurityErrorEvent.SECURITY_ERROR,onError);
			loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,onError);
			loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS,onProgress);
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE,onLoadOver);
		}
		
		private function onLoadOver(e:Event):void{
			if(isLoader){
				loadedResMap.put(Utils.getNameExt(loadingURI),loader.contentLoaderInfo.content);
			}else{
				loadedResMap.put(Utils.getNameExt(loadingURI),urlLoader.data);
			}
			this.loadNext();
		}
		
		private function onProgress(e:ProgressEvent):void{
			var per:Number = currReceiver.per * e.bytesLoaded / e.bytesTotal + currReceiver.perAll;
			currReceiver && currReceiver.progressCallback && currReceiver.progressCallback(per);
		}
		
		private function onError(e:*):void{
			trace(e);
			currReceiver && currReceiver.errorCallback && currReceiver.errorCallback();
		}
		
		/**
		 *开始加载资源 
		 * 
		 */             
		private function loadNext():void{
			if(currReceiver){
				if(currReceiver.hasNext()){
					isLoading = true;
					this._load(currReceiver.next());
				}else {
					var keys:Array =  loadedResMap.getKeys();
					var ext:String;
					var name:String;
					var atlas:TextureAtlas;
					for each (var key:String in keys){
						ext = Utils.getExt(key);
						name = Utils.getName(key);
						if(checkAtlas(name,ext)){
							atlas = new TextureAtlas(Texture.fromBitmap(loadedResMap.get(resName),false),XML(loadedResMap.get(key)));
							ResManager.me.addTextureAtlas(name,atlas);
						}else if(checkTexture(name,ext)){ //检查单个文件的
							ResManager.me.addTexture(name,Texture.fromBitmap(loadedResMap.get(key),false));
						}
					}
					currReceiver.overCallback && currReceiver.overCallback();
					loadedResMap.clear();
					currReceiver = null;
					loadNext();
				}
			}else if(resReceiverList.length > 0){
				currReceiver = resReceiverList.pop();
				loadNext();
			}else{
				isLoading = false;
			}
		}
		
		private var resName:String;
		private function checkAtlas(name:String,ext:String):Boolean{
			var flag:Boolean = ext == URLType.XML;
			if(flag){
				resName = name +"."+ URLType.PNG;
				if(loadedResMap.hasKey(resName)){
					return true;
				}
				resName = name +"."+ URLType.ATF;
				if(loadedResMap.hasKey(resName)){
					return true;
				}
				resName = name +"."+ URLType.JPG;
				if(loadedResMap.hasKey(resName)){
					return true;
				}
				return false;
			}
			return flag;
		}
		private function checkTexture(name:String,ext:String):Boolean{
			var flag:Boolean = (ext == URLType.PNG)||(ext == URLType.ATF)||(ext == URLType.JPG);
			if(flag){
				resName = name +"."+ URLType.XML;
				if(!loadedResMap.hasKey(resName)){
					return true;
				}
				return false;
			}
			return flag;
		}
		
		/**
		 *真正的判断加载的方法 
		 */			
		private function _load(url:String):void{
			this.loadingURI = url;
			var ext:String = Utils.getExt(url);
			var request:URLRequest = new URLRequest(url);
			switch(ext)
			{
				case URLType.XML:
					urlLoader.load(request);
					isLoader = false;
					break;
				case URLType.ATF:
				case URLType.JPG:
				case URLType.PNG:
					loader.load(request);
					isLoader = true;
					break;
			}
		}
		
		public static function get instance():LoadManager{
			return myinstance;
		}
		
		/**
		 *添加资源进行 
		 * @param res
		 * 
		 */             
		public function add(res:*,overCallback:Function = null,progressCallback:Function = null,
							errorCallback:Function = null, order:int = 0):void{
			if(!res || res.length ==0){
				overCallback && overCallback();
				return;
			}
			var receiver:Receiver = new Receiver(res,overCallback,progressCallback,errorCallback,order);
			resReceiverList.push(receiver);
			resReceiverList.sort(_compareReceiverOrder);
			if(!isLoading){
				this.loadNext();
			}
		}
		
		
		private function _compareReceiverOrder(r1:Receiver,r2:Receiver):int{
			if(r1.order>r2.order){
				return 1;
			}else if(r1.order<r2.order){
				return -1;
			}
			return 0;
		}
	}
}